#!/usr/bin/env node

/**
 * Development script for Tauri Modern Template
 * Provides enhanced development experience with additional features
 */

import { spawn, exec } from 'child_process';
import fs from 'fs';
import path from 'path';
import os from 'os';

// Colors for console output
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  magenta: '\x1b[35m',
  cyan: '\x1b[36m',
};

function log(message, color = colors.reset) {
  console.log(`${color}${message}${colors.reset}`);
}

function logInfo(message) {
  log(`ℹ ${message}`, colors.blue);
}

function logSuccess(message) {
  log(`✓ ${message}`, colors.green);
}

function logWarning(message) {
  log(`⚠ ${message}`, colors.yellow);
}

function logError(message) {
  log(`✗ ${message}`, colors.red);
}

// Check if required tools are installed
function checkPrerequisites() {
  logInfo('Checking prerequisites...');
  
  const requiredTools = [
    { name: 'Node.js', command: 'node --version' },
    { name: 'npm', command: 'npm --version' },
    { name: 'Rust', command: 'rustc --version' },
    { name: 'Cargo', command: 'cargo --version' },
  ];

  for (const tool of requiredTools) {
    try {
      require('child_process').execSync(tool.command, { stdio: 'ignore' });
      logSuccess(`${tool.name} is installed`);
    } catch (error) {
      logError(`${tool.name} is not installed or not in PATH`);
      process.exit(1);
    }
  }
}

// Install dependencies if needed
function installDependencies() {
  logInfo('Checking dependencies...');
  
  if (!fs.existsSync('node_modules')) {
    logInfo('Installing frontend dependencies...');
    try {
      require('child_process').execSync('npm install', { stdio: 'inherit' });
      logSuccess('Frontend dependencies installed');
    } catch (error) {
      logError('Failed to install frontend dependencies');
      process.exit(1);
    }
  }

  // Check if Cargo.lock exists in src-tauri
  if (!fs.existsSync('src-tauri/Cargo.lock')) {
    logInfo('Installing Rust dependencies...');
    try {
      require('child_process').execSync('cargo check', { 
        cwd: 'src-tauri',
        stdio: 'inherit' 
      });
      logSuccess('Rust dependencies installed');
    } catch (error) {
      logError('Failed to install Rust dependencies');
      process.exit(1);
    }
  }
}

// Setup development environment
function setupDevEnvironment() {
  logInfo('Setting up development environment...');
  
  // Create .env.local if it doesn't exist
  const envLocalPath = '.env.local';
  if (!fs.existsSync(envLocalPath)) {
    const envContent = `# Development environment variables
VITE_APP_NAME=Tauri Modern Template
VITE_APP_VERSION=1.0.0
VITE_DEV_MODE=true
`;
    fs.writeFileSync(envLocalPath, envContent);
    logSuccess('Created .env.local file');
  }

  // Create logs directory
  const logsDir = 'logs';
  if (!fs.existsSync(logsDir)) {
    fs.mkdirSync(logsDir);
    logSuccess('Created logs directory');
  }
}

// Start development server
function startDevelopment() {
  logInfo('Starting Vite development server...');

  const args = process.argv.slice(2);
  const viteArgs = ['vite', '--port', '3000', '--host'];

  // Add any additional arguments
  if (args.includes('--debug')) {
    viteArgs.push('--debug');
  }

  if (args.includes('--verbose')) {
    viteArgs.push('--verbose');
  }

  const devProcess = spawn('npx', viteArgs, {
    stdio: 'inherit',
    shell: true,
  });

  devProcess.on('close', (code) => {
    if (code !== 0) {
      logError(`Development server exited with code ${code}`);
      process.exit(code);
    }
  });

  // Handle graceful shutdown
  process.on('SIGINT', () => {
    logInfo('Shutting down development server...');
    devProcess.kill('SIGINT');
  });

  process.on('SIGTERM', () => {
    logInfo('Shutting down development server...');
    devProcess.kill('SIGTERM');
  });
}

// Clean build artifacts
function clean() {
  logInfo('Cleaning build artifacts...');
  
  const dirsToClean = [
    'dist',
    'src-tauri/target',
    'node_modules/.vite',
  ];

  for (const dir of dirsToClean) {
    if (fs.existsSync(dir)) {
      fs.rmSync(dir, { recursive: true, force: true });
      logSuccess(`Cleaned ${dir}`);
    }
  }
}

// Show help information
function showHelp() {
  console.log(`
${colors.bright}Tauri Modern Template Development Script${colors.reset}

${colors.cyan}Usage:${colors.reset}
  npm run dev [options]

${colors.cyan}Options:${colors.reset}
  --debug     Enable debug mode
  --verbose   Enable verbose output
  --clean     Clean build artifacts before starting
  --help      Show this help message

${colors.cyan}Examples:${colors.reset}
  npm run dev
  npm run dev -- --debug
  npm run dev -- --clean --verbose
`);
}

// Main function
function main() {
  const args = process.argv.slice(2);

  if (args.includes('--help')) {
    showHelp();
    return;
  }

  if (args.includes('--clean')) {
    clean();
  }

  checkPrerequisites();
  installDependencies();
  setupDevEnvironment();
  startDevelopment();
}

export {
  checkPrerequisites,
  installDependencies,
  setupDevEnvironment,
  startDevelopment,
  clean,
};

main();